//
//  TJVideoPreviewController.m
//  BaoDian
//
//  Created by mac on 2024/8/17.
//

#import "TJVideoPreviewController.h"
#import "TJStyle1Button.h"
#import "TJVideoCoverDownloader.h"
#import "ZFAVPlayerManager.h"
#import "TJPlayerControlView.h"
#import "ZFPlayerConst.h"
#import "ZFUtilities.h"
#import "UIView+ZFFrame.h"
#import "TJPublishVideoController.h"
#import "TJVideoPlayController.h"
#import "TJTimer.h"
#import "TJFontStyle.h"

@interface TJVideoPreviewController ()

@property (nonatomic, weak) UIImageView *coverImageView;
@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, weak) UIView *titleView;
@property (nonatomic, strong) NSString *Id;
@property (nonatomic, strong) TJTimer *timer;
@property (nonatomic, strong) TJFontStyle *fontStyle;

@end

@implementation TJVideoPreviewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    TJPreviewEffectController *previewEffectController = [[TJPreviewEffectController alloc] init];
//    [coverImageView addSubview:previewEffectController.view];
//    [self addChildViewController:previewEffectController];
//    [previewEffectController.view mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.offset(0);
//    }];
//    _previewEffectController = previewEffectController;
    
    
    TJStyle1Button *saveButton = [TJStyle1Button buttonWithSuperView:self.view font:UIFontMediumMake(16) color:nil title:@"保存"];
    [saveButton addTarget:self action:@selector(didClickSaveButton) forControlEvents:UIControlEventTouchUpInside];
    [saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(16);
        make.height.offset(buttonHeight);
        make.bottom.inset(TabbarSafeBottomMargin + 10);
    }];
    
    UIImageView *coverImageView = [UIImageView addToView:self.view];
    coverImageView.userInteractionEnabled = YES;
    coverImageView.backgroundColor = UIColor.blackColor;
    coverImageView.image = self.coverImage;
    coverImageView.contentMode = UIViewContentModeScaleAspectFit;
    CGFloat width = KScreenWidth;
    coverImageView.clipsToBounds = YES;
    [coverImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(width);
        make.centerX.offset(0);
        make.top.offset(KNavBarHight);
        make.bottom.equalTo(saveButton.mas_top).inset(10);
    }];
    _coverImageView = coverImageView;
    
    UIView *titleView = [UIView addToView:coverImageView];
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    
    _titleView = titleView;
    
    UIImageView *playerIconView = [UIImageView addToView:coverImageView];
    [playerIconView addTapGesturesWithTarget:self action:@selector(tapPlayerView)];
    playerIconView.image = [UIImage imageNamed:@"videoPlayer_icon"];
    [playerIconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
    }];
    
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
    
    UILabel *lastLabel = nil;

    for (NSDictionary *  _Nonnull obj in self.titleList) {
        
        NSDictionary *style = obj[@"style"];
        
        NSInteger fontSize = ([style[@"fontSize"] intValue] * self.titleView.tj_width / 1080.0);
        NSInteger strokeWidth = [style[@"outline"] intValue] / 1.5;
        NSInteger shadowBlurRadius = [style[@"shadow"] intValue] / 1.5;

        UILabel *titleLabel = [UILabel lableWithSuperView:self.titleView font:UIFontMake(fontSize) color:UIColorMakeWithHexString(style[@"fontColor"]) title:obj[@"title"] textAlignment:NSTextAlignmentCenter];
        if ([style[@"fontItalic"] boolValue]) {
            CGAffineTransform matrix = CGAffineTransformMake(1, 0, tanf(-5 * (CGFloat)M_PI / 180), 1, 0, 0);
            titleLabel.transform = matrix;
        }
        titleLabel.numberOfLines = 0;
        CGFloat bottomMargin =  [style[@"marginBottom"] intValue] / 1920.0 * self.titleView.tj_height;

        titleLabel.attributedText = [self.fontStyle setTextStyleWithText:obj[@"title"] textColor:style[@"fontColor"] fontName:style[@"font"] fontSize:fontSize strokeColor:style[@"outlineColour"] strokeWidth:strokeWidth shadowColor:style[@"backColour"] shadowBlurRadius:shadowBlurRadius isItalic:[style[@"fontItalic"] boolValue] isBold:[style[@"fontBold"] boolValue ] borderStyle:[style[@"borderStyle"] intValue] underline:[style[@"fontUnderline"] boolValue]];
        [titleLabel sizeToFit];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.offset(0);
            if (titleLabel.tj_width + 8 > KScreenWidth) {
                make.width.offset(KScreenWidth);
            } else {
                make.width.offset(titleLabel.tj_width + 8);
            }
           
            make.bottom.inset(bottomMargin);
            make.height.offset(titleLabel.tj_height);
        }];
        lastLabel = titleLabel;
    }
}



- (void)tapPlayerView {
    TJVideoPlayController *videoPlayController = [[TJVideoPlayController alloc] init];
    videoPlayController.localPath = self.videoURL.path;
    videoPlayController.coverImage = self.coverImage;
    [self presentViewController:videoPlayController animated:YES completion:nil];
}

- (void)queryVideoResult {
    [TJTemplatePresent queryVideoResultDataWithId:self.Id complete:^(NSDictionary * _Nonnull data, NSError * _Nullable error) {
        if (error) {
            [TJHUD showMessage:error.localizedFailureReason];
            return;
        }
        
        NSInteger status = [data[@"status"] intValue];
        if (status == 2) {
            [TJHUD hiddenLoadingInView:self.view];
            [self.timer cancel];
            self.timer = nil;
            TJPublishVideoController *publishVideoController = [[TJPublishVideoController alloc] init];
            publishVideoController.data = data;
            publishVideoController.model = self.model;
            publishVideoController.detailData = self.detailData;
            publishVideoController.materialJsonObj = self.materialJsonObj;
            [self.navigationController pushViewController:publishVideoController];
            return;
        }
    }];
}

- (void)didClickSaveButton {
    [TJHUD showLoadingInView:self.view];
    for (NSMutableDictionary *dict in self.titleList) {
        NSString *title = dict[@"title"];
        title = [title stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
        dict[@"title"] = title;
    }
    
    NSLog(@"Json_dict = %@", self.titleList.mj_JSONString);

    self.materialJsonObj[@"titleList"] = self.titleList;
    [TJTemplatePresent saveTemplateDetailDataWithId:self.model.Id videoId:self.videoDict[@"id"] materialJsonObj:self.materialJsonObj complete:^(NSDictionary * _Nonnull data, NSError * _Nullable error) {
        if (error) {
            return;
        }
        
        self.Id = (NSString *)data;
        TJWeakify(self)
        [self.timer start_SEC:1 ongoing:^{
            [weakself queryVideoResult];
        }];
    }];
 
}

- (TJFontStyle *)fontStyle {
    if (!_fontStyle) {
        _fontStyle = [[TJFontStyle alloc] init];
    }
    return _fontStyle;
}

- (TJTimer *)timer {
    if (!_timer) {
        _timer = [TJTimer timer];
    }
    return _timer;
}

 @end
